//
// Created by LiuYou on 2021/8/5.
//

#include <cstdio>
#include <cstdlib>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctime>
#include "Protocol.hpp"


int main(int argc, char** argv) {
    if (argc < 2) {
        fprintf( stderr, "Usage...\n" );
        exit( 1 );
    }
    int socketFd = socket( PF_INET, SOCK_STREAM, 0 );
    if (socketFd < 0) {
        perror( "socket()" );
        exit( 1 );
    }

//    bind();

    struct sockaddr_in remoteAddress{
            .sin_family=AF_INET,
            .sin_port=htons( atoi( SERVER_PORT ))
    };
    inet_pton( AF_INET, argv[1], &remoteAddress.sin_addr );
    int ret = connect( socketFd, (sockaddr*) &remoteAddress, sizeof( remoteAddress ));
    if (ret < 0) {
        perror( "connect()" );
        exit( 1 );
    }
    FILE* fp = fdopen( socketFd, "r+" );
    if (fp == nullptr) {
        perror( "fdopen()" );
        exit( 1 );
    }
    long long stamp;
    if (fscanf( fp, FMT_STAMP, &stamp ) < 1) {
        fprintf( stderr, "Bad format!\n" );
    } else {
        fprintf( stdout, "stamp = %lld\n", stamp );
    }

    fclose( fp );

//    recv();

//    close();
    exit( 0 );
}